package com.icss.th.common.util;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class StringUtil 
{
	private static final String regEx_script = "<script[^>]*?>[\\s\\S]*?<\\/script>"; // 定义script的正则表达式    
	
	private static final String regEx_style = "<style[^>]*?>[\\s\\S]*?<\\/style>"; // 定义style的正则表达式   
	
	private static final String regEx_html = "<[^>]+>"; // 定义HTML标签的正则表达式
	
	/**
	 * 过滤html标签
	 * @param htmlStr
	 * @return
	 */
	public static String delHTMLTag(String htmlStr) 
	{        
		Pattern p_script = Pattern.compile(regEx_script, Pattern.CASE_INSENSITIVE);        
		Matcher m_script = p_script.matcher(htmlStr);        
		htmlStr = m_script.replaceAll(""); // 过滤script标签        
		Pattern p_style = Pattern.compile(regEx_style, Pattern.CASE_INSENSITIVE);        
		Matcher m_style = p_style.matcher(htmlStr);        
		htmlStr = m_style.replaceAll(""); // 过滤style标签        
		Pattern p_html = Pattern.compile(regEx_html, Pattern.CASE_INSENSITIVE);        
		Matcher m_html = p_html.matcher(htmlStr);        
		htmlStr = m_html.replaceAll(""); // 过滤html标签        
		htmlStr = htmlStr.replaceAll("\r", "");
		htmlStr = htmlStr.replaceAll("\n", "");
		return htmlStr.trim(); 
	}
	
	/**
	 * 截取字符串　超出的字符用symbol代替 　　
	 * @param len字符串长度　长度计量单位为一个GBK汉字　　两个英文字母计算为一个单位长度
	 * @param str
	 * @param symbol
	 * @return
	 */
	public static String getLimitLengthString(String str, int len, String symbol) {
		int iLen = len * 2;
		int counterOfDoubleByte = 0;
		String strRet = "";
		try {
			if (str != null) {
				byte[] b = str.getBytes("GBK");
				if (b.length <= iLen) {
					return str;
				}
				for (int i = 0; i < iLen; i++) {
					if (b[i] < 0) {
						counterOfDoubleByte++;
					}
				}
				if (counterOfDoubleByte % 2 == 0) {
					strRet = new String(b, 0, iLen, "GBK") + symbol;
					return strRet;
				} else {
					strRet = new String(b, 0, iLen - 1, "GBK") + symbol;
					return strRet;
				}
			} else {
				return "";
			}
		} catch (Exception ex) {
			return str.substring(0, len);
		} finally {
			strRet = null;
		}
	}
	
	/**
	 * 规整字符串
	 * @param s
	 * @return
	 */
	public static String format(String s)
	{
		if (isEmpty(s)) return "";
		return s.trim();
	}
	
	/**
	 * 判断字符串为空或null
	 * @param s
	 * @return
	 */
	public static boolean isEmpty(String s)
	{
		return s == null || s.isEmpty();
	}
	
	public static void main(String[] args){
		String str = "2013年会计从业《会计基础》冲刺试卷 <1>详情";
		System.out.println(StringUtil.getLimitLengthString(str, 5, "..."));
	}
	
	
}
